import React, { useState, useMemo, useCallback, useRef, useEffect } from 'react'
import { VariableSizeList as List, ListChildComponentProps } from 'react-window'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { Eye, Copy, ChevronRight, ChevronDown, Search, Filter, Table, List as ListIcon } from 'lucide-react'
import { KafkaMessage } from '@/stores/kafkaStore'
import EnhancedSearch, { SearchOptions, HighlightText } from './EnhancedSearch'
import TableModeViewer from './TableModeViewer'
import toast from 'react-hot-toast'

interface MessageTableProps {
  messages: KafkaMessage[]
  loading?: boolean
  enableVirtualization?: boolean
  enableSearch?: boolean
  maxHeight?: number
  viewMode?: ViewMode
  onViewModeChange?: (mode: ViewMode) => void
}

type ViewMode = 'list' | 'table'

interface ExpandedRows {
  [key: string]: boolean
}

// 虚拟化行组件
const VirtualizedMessageRow = React.memo(({ index, style, data }: ListChildComponentProps) => {
  const {
    filteredMessages,
    expandedRows,
    toggleRow,
    copyToClipboard,
    formatValue,
    formatTimestamp,
    getMessageId
  } = data

  const message = filteredMessages[index]
  const messageId = getMessageId(message, index)
  const isExpanded = expandedRows[messageId]

  const valuePreview = typeof message.value === 'object'
    ? JSON.stringify(message.value).slice(0, 80) + '...'
    : String(message.value).slice(0, 80) + (String(message.value).length > 80 ? '...' : '')

  return (
    <div style={style} className="border-b border-gray-200 bg-white">
      {/* 主行 */}
      <div className="flex items-center h-[60px] px-4 hover:bg-gray-50 relative z-10">
        {/* 展开按钮 */}
        <div className="w-8 flex-shrink-0">
          <button
            onClick={() => toggleRow(messageId)}
            className="p-1 hover:bg-gray-100 rounded"
          >
            {isExpanded ? (
              <ChevronDown className="h-4 w-4" />
            ) : (
              <ChevronRight className="h-4 w-4" />
            )}
          </button>
        </div>

        {/* 时间戳 */}
        <div className="w-40 flex-shrink-0 text-sm text-gray-600">
          {formatTimestamp(message.timestamp)}
        </div>

        {/* 分区 */}
        <div className="w-16 flex-shrink-0">
          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
            {message.partition}
          </span>
        </div>

        {/* 偏移量 */}
        <div className="w-24 flex-shrink-0 font-mono text-sm">
          {message.offset}
        </div>

        {/* Key */}
        <div className="w-32 flex-shrink-0">
          {message.key ? (
            <span className="font-mono text-xs bg-gray-100 px-2 py-1 rounded truncate block">
              {data.searchOptions?.query && data.searchOptions.highlightResults ? (
                <HighlightText
                  text={message.key}
                  searchQuery={data.searchOptions.query}
                  caseSensitive={data.searchOptions.caseSensitive}
                  useRegex={data.searchOptions.useRegex}
                />
              ) : (
                message.key
              )}
            </span>
          ) : (
            <span className="text-gray-400">-</span>
          )}
        </div>

        {/* Value预览 */}
        <div className="flex-1 min-w-0 mr-4">
          <div className="font-mono text-sm text-gray-700 truncate">
            {data.searchOptions?.query && data.searchOptions.highlightResults ? (
              <HighlightText
                text={valuePreview}
                searchQuery={data.searchOptions.query}
                caseSensitive={data.searchOptions.caseSensitive}
                useRegex={data.searchOptions.useRegex}
              />
            ) : (
              valuePreview
            )}
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="w-10 flex-shrink-0">
          <button
            onClick={() => copyToClipboard(formatValue(message.value))}
            className="p-1 hover:bg-gray-100 rounded"
            title="复制Value"
          >
            <Copy className="h-4 w-4" />
          </button>
        </div>
      </div>

      {/* 展开内容 */}
      {isExpanded && (
        <div className="px-4 pb-4 bg-gray-50 border-t relative z-0">
          <div className="space-y-3 py-3">
            {/* Key详情 */}
            {message.key && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-1">Key:</h4>
                <pre className="bg-white p-2 rounded border text-xs font-mono overflow-x-auto max-h-16 overflow-y-auto">
                  {message.key}
                </pre>
              </div>
            )}

            {/* Value详情 */}
            <div>
              <h4 className="text-sm font-medium text-gray-700 mb-1">Value:</h4>
              <pre className="bg-white p-2 rounded border text-xs font-mono overflow-x-auto max-h-32 overflow-y-auto">
                {formatValue(message.value)}
              </pre>
            </div>

            {/* Headers */}
            {Object.keys(message.headers).length > 0 && (
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-1">Headers:</h4>
                <pre className="bg-white p-2 rounded border text-xs font-mono overflow-x-auto max-h-16 overflow-y-auto">
                  {JSON.stringify(message.headers, null, 2)}
                </pre>
              </div>
            )}

            {/* 元数据 */}
            <div>
              <h4 className="text-sm font-medium text-gray-700 mb-1">元数据:</h4>
              <div className="bg-white p-2 rounded border text-xs">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                  <div>
                    <span className="text-gray-500">Topic:</span>
                    <div className="font-mono text-xs">{message.topic}</div>
                  </div>
                  <div>
                    <span className="text-gray-500">分区:</span>
                    <div className="font-mono text-xs">{message.partition}</div>
                  </div>
                  <div>
                    <span className="text-gray-500">偏移量:</span>
                    <div className="font-mono text-xs">{message.offset}</div>
                  </div>
                  <div>
                    <span className="text-gray-500">时间戳:</span>
                    <div className="font-mono text-xs">{message.timestamp || '-'}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
})

VirtualizedMessageRow.displayName = 'VirtualizedMessageRow'

export default function MessageTable({
  messages,
  loading = false,
  enableVirtualization = true,
  enableSearch = true,
  maxHeight = 600,
  viewMode: propViewMode,
  onViewModeChange
}: MessageTableProps) {
  const [expandedRows, setExpandedRows] = useState<ExpandedRows>({})
  const [searchOptions, setSearchOptions] = useState<SearchOptions>({
    query: '',
    searchIn: 'both',
    caseSensitive: false,
    useRegex: false,
    highlightResults: true
  })
  const [viewMode, setViewMode] = useState<ViewMode>(propViewMode || 'list')
  const [isSearching, setIsSearching] = useState(false)
  const listRef = useRef<List>(null)

  // 同步外部传入的viewMode
  useEffect(() => {
    if (propViewMode) {
      setViewMode(propViewMode)
    }
  }, [propViewMode])

  // 处理视图模式变化
  const handleViewModeChange = (mode: ViewMode) => {
    setViewMode(mode)
    onViewModeChange?.(mode)
  }

  // 过滤消息
  const filteredMessages = useMemo(() => {
    if (!searchOptions.query.trim()) return messages

    return messages.filter(message => {
      const keyStr = message.key || ''
      const valueStr = JSON.stringify(message.value)

      let searchTargets: string[] = []

      // 根据搜索范围确定搜索目标
      switch (searchOptions.searchIn) {
        case 'key':
          searchTargets = [keyStr]
          break
        case 'value':
          searchTargets = [valueStr]
          break
        case 'both':
        default:
          searchTargets = [keyStr, valueStr]
          break
      }

      // 执行搜索
      return searchTargets.some(target => {
        if (!target) return false

        const searchText = searchOptions.caseSensitive ? target : target.toLowerCase()
        const query = searchOptions.caseSensitive ? searchOptions.query : searchOptions.query.toLowerCase()

        if (searchOptions.useRegex) {
          try {
            const flags = searchOptions.caseSensitive ? 'g' : 'gi'
            const regex = new RegExp(searchOptions.query, flags)
            return regex.test(target)
          } catch {
            return false
          }
        } else {
          return searchText.includes(query)
        }
      })
    })
  }, [messages, searchOptions])

  const toggleRow = useCallback((messageId: string) => {
    setExpandedRows(prev => ({
      ...prev,
      [messageId]: !prev[messageId]
    }))

    // 重置虚拟列表缓存，以便重新计算行高
    if (listRef.current) {
      listRef.current.resetAfterIndex(0)
    }
  }, [])

  const copyToClipboard = useCallback((text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      toast.success('已复制到剪贴板')
    }).catch(() => {
      toast.error('复制失败')
    })
  }, [])

  const formatValue = useCallback((value: any) => {
    if (typeof value === 'object') {
      return JSON.stringify(value, null, 2)
    }
    return String(value)
  }, [])

  const formatTimestamp = useCallback((timestamp?: number) => {
    if (!timestamp) return '-'
    return format(new Date(timestamp), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
  }, [])

  const getMessageId = useCallback((message: KafkaMessage, index: number) => {
    return `${message.topic}-${message.partition}-${message.offset}-${index}`
  }, [])

  // 计算动态行高
  const getItemSize = useCallback((index: number) => {
    if (index >= filteredMessages.length) return 60

    const message = filteredMessages[index]
    const messageId = getMessageId(message, index)
    const isExpanded = expandedRows[messageId]

    // 基础行高60px，展开时根据内容动态计算
    if (!isExpanded) return 60

    // 展开时的高度计算：
    // 基础行 60px + 展开内容区域
    let expandedHeight = 60 + 40 // 基础 + padding

    // Key部分高度 (如果有key)
    if (message.key) {
      expandedHeight += 80 // 标题 + 内容区域
    }

    // Value部分高度 (必有)
    expandedHeight += 120 // 标题 + 内容区域

    // Headers部分高度 (如果有headers)
    if (Object.keys(message.headers).length > 0) {
      expandedHeight += 80 // 标题 + 内容区域
    }

    // 元数据部分高度 (必有)
    expandedHeight += 100 // 标题 + 网格内容

    return Math.min(expandedHeight, 400) // 最大高度限制为400px
  }, [filteredMessages, expandedRows, getMessageId])

  // 传递给虚拟化行的数据
  const itemData = useMemo(() => ({
    filteredMessages,
    expandedRows,
    toggleRow,
    copyToClipboard,
    formatValue,
    formatTimestamp,
    getMessageId,
    searchOptions
  }), [filteredMessages, expandedRows, toggleRow, copyToClipboard, formatValue, formatTimestamp, getMessageId, searchOptions])

  // 滚动到顶部
  const scrollToTop = useCallback(() => {
    if (listRef.current) {
      listRef.current.scrollToItem(0)
    }
  }, [])

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    if (listRef.current && filteredMessages.length > 0) {
      listRef.current.scrollToItem(filteredMessages.length - 1)
    }
  }, [filteredMessages.length])

  // 搜索处理
  const handleSearch = useCallback(async (options: SearchOptions) => {
    setIsSearching(true)
    setSearchOptions(options)

    // 模拟搜索延迟
    setTimeout(() => {
      setIsSearching(false)
    }, 100)
  }, [])

  const handleClearSearch = useCallback(() => {
    setSearchOptions(prev => ({ ...prev, query: '' }))
  }, [])

  // 当消息更新时，默认滚动到顶部（最新消息在顶部）
  useEffect(() => {
    if (enableVirtualization && listRef.current && messages.length > 0 && viewMode === 'list') {
      // 新消息加载完成后，滚动到顶部显示最新消息
      scrollToTop()
    }
  }, [messages.length, enableVirtualization, scrollToTop, viewMode])

  if (loading) {
    return (
      <div className="card">
        <div className="card-content">
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            <span className="ml-2 text-gray-600">加载中...</span>
          </div>
        </div>
      </div>
    )
  }

  if (messages.length === 0) {
    return (
      <div className="card">
        <div className="card-content">
          <div className="text-center py-12">
            <Eye className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无消息</h3>
            <p className="text-gray-600">选择一个Topic并加载消息或开始实时流式</p>
          </div>
        </div>
      </div>
    )
  }

  // 渲染虚拟化表格
  const renderVirtualizedTable = () => (
    <div className="card">
      {/* 表头和控制 */}
      <div className="card-header">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="card-title">消息列表</h3>
            <p className="card-description">
              共 {messages.length} 条消息
              {searchOptions.query && ` (过滤后 ${filteredMessages.length} 条)`}
            </p>
          </div>

          {/* 视图模式切换 */}
          <div className="flex items-center space-x-2">
            <div className="flex items-center border border-gray-300 rounded-md">
              <button
                onClick={() => handleViewModeChange('list')}
                className={`px-3 py-2 text-sm flex items-center space-x-1 ${
                  viewMode === 'list'
                    ? 'bg-primary-600 text-white'
                    : 'text-gray-600 hover:bg-gray-50'
                }`}
              >
                <ListIcon className="h-4 w-4" />
                <span>列表模式</span>
              </button>
              <button
                onClick={() => handleViewModeChange('table')}
                className={`px-3 py-2 text-sm flex items-center space-x-1 ${
                  viewMode === 'table'
                    ? 'bg-primary-600 text-white'
                    : 'text-gray-600 hover:bg-gray-50'
                }`}
              >
                <Table className="h-4 w-4" />
                <span>表格模式</span>
              </button>
            </div>
          </div>
        </div>

        {/* 搜索组件 */}
        {enableSearch && (
          <EnhancedSearch
            onSearch={handleSearch}
            onClear={handleClearSearch}
            loading={isSearching}
            resultCount={filteredMessages.length}
            totalCount={messages.length}
          />
        )}

        {/* 快速操作 */}
        <div className="flex items-center justify-between mt-4">
          <div className="flex items-center space-x-2">
            <button
              onClick={scrollToTop}
              className="text-sm px-3 py-1 border border-gray-300 rounded hover:bg-gray-50"
            >
              回到顶部
            </button>
            <button
              onClick={scrollToBottom}
              className="text-sm px-3 py-1 border border-gray-300 rounded hover:bg-gray-50"
            >
              跳到底部
            </button>
          </div>

          <div className="text-sm text-gray-500">
            💡 支持虚拟滚动，可流畅展示大量数据
          </div>
        </div>
      </div>

      {/* 表格头部 */}
      <div className="border-b border-gray-200 bg-gray-50">
        <div className="flex items-center h-[50px] px-4 text-sm font-medium text-gray-700">
          <div className="w-8 flex-shrink-0"></div>
          <div className="w-40 flex-shrink-0">时间戳</div>
          <div className="w-16 flex-shrink-0">分区</div>
          <div className="w-24 flex-shrink-0">偏移量</div>
          <div className="w-32 flex-shrink-0">Key</div>
          <div className="flex-1 min-w-0 mr-4">Value预览</div>
          <div className="w-10 flex-shrink-0">操作</div>
        </div>
      </div>

      {/* 虚拟化列表 */}
      <div className="card-content p-0">
        <List
          ref={listRef}
          height={maxHeight}
          itemCount={filteredMessages.length}
          itemSize={getItemSize}
          itemData={itemData}
          overscanCount={5}
        >
          {VirtualizedMessageRow}
        </List>
      </div>
    </div>
  )

  // 渲染传统表格
  const renderTraditionalTable = () => (
    <div className="card">
      <div className="card-header">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h3 className="card-title">消息列表</h3>
            <p className="card-description">
              共 {messages.length} 条消息
              {searchOptions.query && ` (过滤后 ${filteredMessages.length} 条)`}
            </p>
          </div>

          {/* 视图模式切换 */}
          <div className="flex items-center space-x-2">
            <div className="flex items-center border border-gray-300 rounded-md">
              <button
                onClick={() => handleViewModeChange('list')}
                className={`px-3 py-2 text-sm flex items-center space-x-1 ${
                  viewMode === 'list'
                    ? 'bg-primary-600 text-white'
                    : 'text-gray-600 hover:bg-gray-50'
                }`}
              >
                <ListIcon className="h-4 w-4" />
                <span>列表模式</span>
              </button>
              <button
                onClick={() => handleViewModeChange('table')}
                className={`px-3 py-2 text-sm flex items-center space-x-1 ${
                  viewMode === 'table'
                    ? 'bg-primary-600 text-white'
                    : 'text-gray-600 hover:bg-gray-50'
                }`}
              >
                <Table className="h-4 w-4" />
                <span>表格模式</span>
              </button>
            </div>
          </div>
        </div>

        {/* 搜索组件 */}
        {enableSearch && (
          <EnhancedSearch
            onSearch={handleSearch}
            onClear={handleClearSearch}
            loading={isSearching}
            resultCount={filteredMessages.length}
            totalCount={messages.length}
          />
        )}
      </div>

      <div className="card-content p-0">
        <div className="overflow-x-auto" style={{ maxHeight: maxHeight }}>
          <table className="table">
            <thead className="table-header">
              <tr className="table-row">
                <th className="table-head w-10"></th>
                <th className="table-head">时间戳</th>
                <th className="table-head">分区</th>
                <th className="table-head">偏移量</th>
                <th className="table-head">Key</th>
                <th className="table-head">Value预览</th>
                <th className="table-head w-20">操作</th>
              </tr>
            </thead>
            <tbody className="table-body">
              {filteredMessages.map((message, index) => {
                const messageId = getMessageId(message, index)
                const isExpanded = expandedRows[messageId]
                const valuePreview = typeof message.value === 'object' 
                  ? JSON.stringify(message.value).slice(0, 100) + '...'
                  : String(message.value).slice(0, 100) + (String(message.value).length > 100 ? '...' : '')

                return (
                  <React.Fragment key={messageId}>
                    <tr className="table-row">
                      <td className="table-cell">
                        <button
                          onClick={() => toggleRow(messageId)}
                          className="p-1 hover:bg-gray-100 rounded"
                        >
                          {isExpanded ? (
                            <ChevronDown className="h-4 w-4" />
                          ) : (
                            <ChevronRight className="h-4 w-4" />
                          )}
                        </button>
                      </td>
                      <td className="table-cell text-sm">
                        {formatTimestamp(message.timestamp)}
                      </td>
                      <td className="table-cell">
                        <span className="badge badge-secondary">
                          {message.partition}
                        </span>
                      </td>
                      <td className="table-cell font-mono text-sm">
                        {message.offset}
                      </td>
                      <td className="table-cell">
                        {message.key ? (
                          <span className="font-mono text-sm bg-gray-100 px-2 py-1 rounded">
                            {searchOptions?.query && searchOptions.highlightResults ? (
                              <HighlightText
                                text={message.key}
                                searchQuery={searchOptions.query}
                                caseSensitive={searchOptions.caseSensitive}
                                useRegex={searchOptions.useRegex}
                              />
                            ) : (
                              message.key
                            )}
                          </span>
                        ) : (
                          <span className="text-gray-400">-</span>
                        )}
                      </td>
                      <td className="table-cell">
                        <div className="font-mono text-sm max-w-md truncate">
                          {searchOptions?.query && searchOptions.highlightResults ? (
                            <HighlightText
                              text={valuePreview}
                              searchQuery={searchOptions.query}
                              caseSensitive={searchOptions.caseSensitive}
                              useRegex={searchOptions.useRegex}
                            />
                          ) : (
                            valuePreview
                          )}
                        </div>
                      </td>
                      <td className="table-cell">
                        <button
                          onClick={() => copyToClipboard(formatValue(message.value))}
                          className="p-1 hover:bg-gray-100 rounded"
                          title="复制Value"
                        >
                          <Copy className="h-4 w-4" />
                        </button>
                      </td>
                    </tr>

                    {isExpanded && (
                      <tr className="table-row bg-gray-50">
                        <td className="table-cell"></td>
                        <td colSpan={6} className="table-cell">
                          <div className="space-y-4 py-4">
                            {/* Key详情 */}
                            {message.key && (
                              <div>
                                <h4 className="text-sm font-medium text-gray-700 mb-2">Key:</h4>
                                <pre className="bg-white p-3 rounded border text-sm font-mono overflow-x-auto">
                                  {message.key}
                                </pre>
                              </div>
                            )}
                            
                            {/* Value详情 */}
                            <div>
                              <h4 className="text-sm font-medium text-gray-700 mb-2">Value:</h4>
                              <pre className="bg-white p-3 rounded border text-sm font-mono overflow-x-auto max-h-64 overflow-y-auto">
                                {formatValue(message.value)}
                              </pre>
                            </div>
                            
                            {/* Headers */}
                            {Object.keys(message.headers).length > 0 && (
                              <div>
                                <h4 className="text-sm font-medium text-gray-700 mb-2">Headers:</h4>
                                <pre className="bg-white p-3 rounded border text-sm font-mono overflow-x-auto">
                                  {JSON.stringify(message.headers, null, 2)}
                                </pre>
                              </div>
                            )}
                            
                            {/* 元数据 */}
                            <div>
                              <h4 className="text-sm font-medium text-gray-700 mb-2">元数据:</h4>
                              <div className="bg-white p-3 rounded border text-sm">
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                                  <div>
                                    <span className="text-gray-500">Topic:</span>
                                    <div className="font-mono">{message.topic}</div>
                                  </div>
                                  <div>
                                    <span className="text-gray-500">分区:</span>
                                    <div className="font-mono">{message.partition}</div>
                                  </div>
                                  <div>
                                    <span className="text-gray-500">偏移量:</span>
                                    <div className="font-mono">{message.offset}</div>
                                  </div>
                                  <div>
                                    <span className="text-gray-500">时间戳:</span>
                                    <div className="font-mono">{message.timestamp || '-'}</div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                )
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )

  // 主渲染逻辑
  if (loading) {
    return (
      <div className="card">
        <div className="card-content">
          <div className="flex items-center justify-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            <span className="ml-2 text-gray-600">加载中...</span>
          </div>
        </div>
      </div>
    )
  }

  if (messages.length === 0) {
    return (
      <div className="card">
        <div className="card-content">
          <div className="text-center py-12">
            <Eye className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">暂无消息</h3>
            <p className="text-gray-600">选择一个Topic并加载消息或开始实时流式</p>
          </div>
        </div>
      </div>
    )
  }

  // 根据视图模式渲染不同的组件
  if (viewMode === 'table') {
    return (
      <div className="card">
        <div className="card-header">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="card-title">表格模式</h3>
              <p className="card-description">
                共 {messages.length} 条消息
                {searchOptions.query && ` (过滤后 ${filteredMessages.length} 条)`}
              </p>
            </div>

            {/* 视图模式切换 */}
            <div className="flex items-center space-x-2">
              <div className="flex items-center border border-gray-300 rounded-md">
                <button
                  onClick={() => handleViewModeChange('list')}
                  className="px-3 py-2 text-sm flex items-center space-x-1 text-gray-600 hover:bg-gray-50"
                >
                  <ListIcon className="h-4 w-4" />
                  <span>列表模式</span>
                </button>
                <button
                  onClick={() => handleViewModeChange('table')}
                  className="px-3 py-2 text-sm flex items-center space-x-1 bg-primary-600 text-white"
                >
                  <Table className="h-4 w-4" />
                  <span>表格模式</span>
                </button>
              </div>
            </div>
          </div>

          {/* 搜索组件 */}
          {enableSearch && (
            <EnhancedSearch
              onSearch={handleSearch}
              onClear={handleClearSearch}
              loading={isSearching}
              resultCount={filteredMessages.length}
              totalCount={messages.length}
            />
          )}
        </div>

        <div className="card-content p-0">
          <TableModeViewer
            messages={filteredMessages}
            searchOptions={searchOptions}
            maxHeight={maxHeight}
            loading={loading}
          />
        </div>
      </div>
    )
  }

  // 根据消息数量和配置决定使用虚拟化还是传统表格
  const shouldUseVirtualization = enableVirtualization && messages.length > 100

  return shouldUseVirtualization ? renderVirtualizedTable() : renderTraditionalTable()
}
